package com.xueyu.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xueyu.dao.privilegesDao;
import com.xueyu.dao.rpDao;
import com.xueyu.domain.rp;
import com.xueyu.domain.CacheManager;
import com.xueyu.domain.privileges;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@CrossOrigin
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private privilegesDao privilegesDao;
    @Autowired
    private rpDao rpDao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ServletContext application = request.getServletContext();
        //获取application对象中保存的系统权限数据
        List<privileges> sysMenu = (List<privileges>) application.getAttribute("sysMenu");
        //2.读取系统权限(系统启动时运行，只会运行一次)
        if (sysMenu == null) {
            QueryWrapper<privileges> queryWrapper = new QueryWrapper<privileges>();
            queryWrapper.gt("parentId", 0);
            sysMenu = privilegesDao.selectList(queryWrapper);
            //保存application对象
            application.setAttribute("sysMenu", sysMenu);
        }



        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sdate = sdf.format(new Date(System.currentTimeMillis()));
        System.out.println("函数开始执行时间:" + sdate);
        String url = request.getServletPath();
        System.out.println("ServletPath=" + request.getServletPath());
        //拦截时要排除静态资源和登录功能（js,css,upload文件夹及/login/login2）
        if (url.startsWith("/js") || url.startsWith("/11011/login") || url.startsWith("/css") || url.startsWith("/roleController/login")) {
            return true;
        }
        String token = (String) CacheManager.get("myData");

        if(token==null && !url.equals("/11011/login")){
            JSONObject resultBean = new JSONObject();
            resultBean.put("code",401);
            resultBean.put("msg","token过期了");
            response.getWriter().println(resultBean.toJSONString());
//            response.getWriter().println(resultBean.toString());
            return false;
        }


        if (token == null) {
            System.out.println("系统未登录。。。");
            return false;
        } else {
            System.out.println("已登录。。。");
        boolean bExists = false;
        for (privileges menu:sysMenu){
            //请求的URL与系统权限表中的数据进行比对，如果找到了，说明需要进行权限控制
            if(url.startsWith(menu.getPath())){//比较sysmenu表的数据是否存在url对应的字符串
                //需要做权限判断
                System.out.println("============"+menu.getPath());
                bExists = true;
                break;
            }
        }
        if(!bExists){
            return true;
        }else{ //要做权限控制
            //用url于当前的用户权限表数据进行比较，如果找不到，说明没有权限
            bExists = false;
            QueryWrapper<rp> queryWrapper = new QueryWrapper<rp>();
            queryWrapper.select("SPID"); // 指定要选择的字段
            queryWrapper.eq("RoleID",token);
            List<rp> SPIDlist= rpDao.selectList(queryWrapper);
            List<Integer> spidList = new ArrayList<>();
            for (rp rpItem : SPIDlist) {
                spidList.add(rpItem.getSPID());
            }

            QueryWrapper<privileges> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("id", spidList); // 使用多个元素作为条件
            List<privileges> resultList = privilegesDao.selectList(queryWrapper2);



            for (privileges menu : resultList){//比较sysrolemenu表的数据是否存在url对应的字符串
                if(url.startsWith(menu.getPath())){
                    //有权限
                    bExists = true;
                    break;
                }
            }
        }

            if(bExists){ //有权限，不拦截
                return true;
            }else{ //没有权限，要进行错误提醒
                request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request,response);
                return false;

            }
//
//    return true;
    }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("函数开始执行时间:"+new Date(System.currentTimeMillis()));
    }
}
